package com.victor.modular.system.controller;

import com.victor.common.controller.BaseController;
import com.victor.common.exception.BizExceptionEnum;
import com.victor.common.exception.BussinessException;
import com.victor.config.properties.VictorProperties;
import com.victor.core.util.FileUtil;
import com.victor.core.util.ToolUtil;
import com.victor.core.util.UtilTrans;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件控制器
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @Resource
    private VictorProperties victorProperties;

    /**
     * 上传附件
     *
     * @author: Jiabin.Zhao
     * @CreationTime: 2017年8月14日 上午10:19:30
     */
    @RequestMapping(method = RequestMethod.POST, path = "/temp/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile file) {
        String originalFilename = file.getOriginalFilename();// 文件名称
        String originalFileText = (originalFilename.substring(0,
                originalFilename.lastIndexOf(".")));// 文件类型
        String originalFileType = (originalFilename.substring(originalFilename
                .lastIndexOf(".")));// 文件类型
        SimpleDateFormat sdf = new SimpleDateFormat("-yyyyMMddHHmmss");
        String fileName = originalFileText + sdf.format(new Date())
                + originalFileType;
        try {
            String fileSavePath = victorProperties.getFileUploadTempPath();
            file.transferTo(new File(fileSavePath + fileName));
        } catch (Exception e) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return fileName;
    }

    /**
     * 返回资源文件
     *
     * @author: Jiabin.Zhao
     * @CreationTime: 2017年9月13日 下午5:10:03
     */
    @RequestMapping("/resource/{fileId:.+}")
    public void renderTempFile(@PathVariable("fileId") String fileId,
                               HttpServletResponse response) {
        String path = victorProperties.getResourcePath() + fileId;
        try {
            byte[] bytes = FileUtil.toByteArray(path);
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载附件
     *
     * @author: Jiabin.Zhao
     * @CreationTime: 2017年8月14日 上午10:19:30
     */
    @RequestMapping(value = "/down", method = {RequestMethod.POST,
            RequestMethod.GET})
    public void down(HttpServletRequest request, HttpServletResponse resp)
            throws IOException {
        String path = UtilTrans.transNullToString(request.getParameter("path"), null);//子文件夹名称
        String fileSavePath = victorProperties.getFileUploadPath();
        if (ToolUtil.isNotEmpty(path)) {
            fileSavePath = fileSavePath + "/" + path + "/";
        }
        String fileName = request.getParameter("fileName");
        File file = new File(fileSavePath + fileName);
        fileName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        resp.setHeader("content-type", "application/octet-stream");
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();// 这里会产生socket write error
                i = bis.read(buff);
            }
        } catch (ClientAbortException e) {
            // org.apache.catalina.connector.ClientAbortException:
            // java.io.IOException: 远程主机强迫关闭了一个现有的连接。
            // 不用捕捉这个异常
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    os.close();
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 预览pdf
     *
     * @author: Jiabin.Zhao
     * @CreationTime: 2017年8月14日 上午10:19:30
     */
    @RequestMapping(value = "/preview", method = {RequestMethod.POST,
            RequestMethod.GET})
    public void hoursDetailExport(HttpServletRequest request,
                                  HttpServletResponse resp) throws IOException {
        String path = UtilTrans.transNullToString(request.getParameter("path"), null);//子文件夹名称
        String fileSavePath = victorProperties.getFileUploadPath();
        if (ToolUtil.isNotEmpty(path)) {
            fileSavePath = fileSavePath + "/" + path + "/";
        }
        String fileName = request.getParameter("fileName");
        File file = new File(fileSavePath + fileName);
        // D:\projects\booth-sales\file
        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        resp.setContentType("application/pdf");
        // 清除首部的空白行。
        resp.reset();
        resp.setHeader("Cache-Control", "max-age=0");
        resp.setCharacterEncoding("UTF-8");
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();// 这里会产生socket write error
                i = bis.read(buff);
            }
        } catch (ClientAbortException e) {
            // org.apache.catalina.connector.ClientAbortException:
            // java.io.IOException: 远程主机强迫关闭了一个现有的连接。
            // 不用捕捉这个异常
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 返回临时文件
     *
     * @Title:
     * @Description:
     * @author: Jiabin.Zhao
     * @CreationTime: 2017年8月14日 下午12:11:45
     */
    @RequestMapping("/temp/{fileId:.+}")
    public void renderTemp(@PathVariable("fileId") String fileId,
                           HttpServletResponse response) {
        String path = victorProperties.getFileUploadTempPath() + fileId;
        try {
            byte[] bytes = FileUtil.toByteArray(path);
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
